import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Tag, message, Tabs, Space, Modal, Rate, Input, Form } from 'antd';
import { FileTextOutlined, StarOutlined } from '@ant-design/icons';
import { getMyTrainings, cancelEnrollment, submitFeedback } from '../../../api/training';

const { TabPane } = Tabs;
const { TextArea } = Input;

/**
 * 我的培训页面
 * 显示员工已报名和已参加的培训
 */
const MyTraining = () => {
    const [loading, setLoading] = useState(false);
    const [myTrainings, setMyTrainings] = useState({
        upcoming: [],
        ongoing: [],
        completed: []
    });
    const [activeKey, setActiveKey] = useState('upcoming');
    const [feedbackVisible, setFeedbackVisible] = useState(false);
    const [currentTraining, setCurrentTraining] = useState(null);
    const [feedbackForm] = Form.useForm();
    const [submitLoading, setSubmitLoading] = useState(false);

    useEffect(() => {
        fetchMyTrainings();
    }, []);

    // 获取我的培训
    const fetchMyTrainings = async () => {
        setLoading(true);
        try {
            const response = await getMyTrainings();
            setMyTrainings(response.data || {
                upcoming: [],
                ongoing: [],
                completed: []
            });
        } catch (error) {
            console.error('获取培训数据失败:', error);
            message.error('获取培训数据失败');
        } finally {
            setLoading(false);
        }
    };

    // 取消报名
    const handleCancel = (record) => {
        Modal.confirm({
            title: '确认取消',
            content: `确定要取消参加"${record.title}"培训吗？`,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                try {
                    await cancelEnrollment(record.enrollment_id);
                    message.success('已取消报名');
                    fetchMyTrainings();
                } catch (error) {
                    console.error('取消报名失败:', error);
                    message.error('取消报名失败');
                }
            }
        });
    };

    // 提交反馈
    const handleFeedbackSubmit = async () => {
        try {
            const values = await feedbackForm.validateFields();
            
            setSubmitLoading(true);
            await submitFeedback({
                training_id: currentTraining.id,
                enrollment_id: currentTraining.enrollment_id,
                rating: values.rating,
                comment: values.comment
            });
            
            message.success('反馈提交成功');
            setFeedbackVisible(false);
            fetchMyTrainings();
        } catch (error) {
            if (error.errorFields) {
                return; // 表单验证失败
            }
            console.error('提交反馈失败:', error);
            message.error('提交反馈失败');
        } finally {
            setSubmitLoading(false);
        }
    };

    // 打开反馈表单
    const handleFeedback = (record) => {
        setCurrentTraining(record);
        setFeedbackVisible(true);
        feedbackForm.resetFields();
    };

    // 查看培训材料
    const handleViewMaterials = (record) => {
        message.info('查看培训材料功能开发中...');
    };

    // 即将开始培训的列
    const upcomingColumns = [
        {
            title: '培训名称',
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: '培训类型',
            dataIndex: 'type',
            key: 'type',
            render: (type) => {
                const colorMap = {
                    '技能培训': 'blue',
                    '管理培训': 'purple',
                    '新员工培训': 'green',
                    '职业发展': 'orange',
                };
                return <Tag color={colorMap[type] || 'default'}>{type}</Tag>;
            },
        },
        {
            title: '开始日期',
            dataIndex: 'start_date',
            key: 'start_date',
        },
        {
            title: '结束日期',
            dataIndex: 'end_date',
            key: 'end_date',
        },
        {
            title: '培训讲师',
            dataIndex: 'instructor',
            key: 'instructor',
        },
        {
            title: '培训地点',
            dataIndex: 'location',
            key: 'location',
        },
        {
            title: '报名状态',
            dataIndex: 'enrollment_status',
            key: 'enrollment_status',
            render: (status) => {
                const statusMap = {
                    'pending': { color: 'orange', text: '待审核' },
                    'approved': { color: 'green', text: '已通过' },
                    'rejected': { color: 'red', text: '已拒绝' },
                };
                
                const { color, text } = statusMap[status] || { color: 'default', text: status };
                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="link" 
                        danger
                        onClick={() => handleCancel(record)}
                        disabled={record.enrollment_status !== 'approved' && record.enrollment_status !== 'pending'}
                    >
                        取消报名
                    </Button>
                </Space>
            ),
        },
    ];

    // 进行中培训的列
    const ongoingColumns = [
        {
            title: '培训名称',
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: '培训类型',
            dataIndex: 'type',
            key: 'type',
            render: (type) => {
                const colorMap = {
                    '技能培训': 'blue',
                    '管理培训': 'purple',
                    '新员工培训': 'green',
                    '职业发展': 'orange',
                };
                return <Tag color={colorMap[type] || 'default'}>{type}</Tag>;
            },
        },
        {
            title: '开始日期',
            dataIndex: 'start_date',
            key: 'start_date',
        },
        {
            title: '结束日期',
            dataIndex: 'end_date',
            key: 'end_date',
        },
        {
            title: '培训地点',
            dataIndex: 'location',
            key: 'location',
        },
        {
            title: '培训进度',
            dataIndex: 'progress',
            key: 'progress',
            render: (progress) => `${progress || 0}%`,
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="primary" 
                        icon={<FileTextOutlined />}
                        onClick={() => handleViewMaterials(record)}
                    >
                        培训材料
                    </Button>
                </Space>
            ),
        },
    ];

    // 已完成培训的列
    const completedColumns = [
        {
            title: '培训名称',
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: '培训类型',
            dataIndex: 'type',
            key: 'type',
            render: (type) => {
                const colorMap = {
                    '技能培训': 'blue',
                    '管理培训': 'purple',
                    '新员工培训': 'green',
                    '职业发展': 'orange',
                };
                return <Tag color={colorMap[type] || 'default'}>{type}</Tag>;
            },
        },
        {
            title: '完成日期',
            dataIndex: 'completion_date',
            key: 'completion_date',
        },
        {
            title: '完成状态',
            dataIndex: 'completion_status',
            key: 'completion_status',
            render: (status) => {
                const statusMap = {
                    'passed': { color: 'green', text: '通过' },
                    'failed': { color: 'red', text: '未通过' },
                    'incomplete': { color: 'orange', text: '未完成' },
                };
                
                const { color, text } = statusMap[status] || { color: 'default', text: status };
                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: '评分',
            dataIndex: 'score',
            key: 'score',
        },
        {
            title: '已反馈',
            dataIndex: 'has_feedback',
            key: 'has_feedback',
            render: (hasFeedback) => (
                hasFeedback ? <Tag color="green">已提交</Tag> : <Tag color="orange">未提交</Tag>
            ),
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="primary" 
                        icon={<FileTextOutlined />}
                        onClick={() => handleViewMaterials(record)}
                    >
                        培训资料
                    </Button>
                    {!record.has_feedback && (
                        <Button 
                            type="primary" 
                            icon={<StarOutlined />}
                            onClick={() => handleFeedback(record)}
                        >
                            提交反馈
                        </Button>
                    )}
                </Space>
            ),
        },
    ];

    return (
        <>
            <Card title="我的培训">
                <Tabs activeKey={activeKey} onChange={setActiveKey}>
                    <TabPane tab="即将开始" key="upcoming">
                        <Table
                            columns={upcomingColumns}
                            dataSource={myTrainings.upcoming}
                            rowKey="id"
                            loading={loading && activeKey === 'upcoming'}
                        />
                    </TabPane>
                    
                    <TabPane tab="进行中" key="ongoing">
                        <Table
                            columns={ongoingColumns}
                            dataSource={myTrainings.ongoing}
                            rowKey="id"
                            loading={loading && activeKey === 'ongoing'}
                        />
                    </TabPane>
                    
                    <TabPane tab="已完成" key="completed">
                        <Table
                            columns={completedColumns}
                            dataSource={myTrainings.completed}
                            rowKey="id"
                            loading={loading && activeKey === 'completed'}
                        />
                    </TabPane>
                </Tabs>
            </Card>

            {/* 反馈表单弹窗 */}
            <Modal
                title="培训反馈"
                open={feedbackVisible}
                onCancel={() => setFeedbackVisible(false)}
                onOk={handleFeedbackSubmit}
                confirmLoading={submitLoading}
            >
                <Form
                    form={feedbackForm}
                    layout="vertical"
                >
                    <Form.Item
                        label="培训名称"
                    >
                        <Input value={currentTraining?.title} disabled />
                    </Form.Item>
                    
                    <Form.Item
                        name="rating"
                        label="培训评分"
                        rules={[{ required: true, message: '请对培训进行评分' }]}
                    >
                        <Rate allowHalf />
                    </Form.Item>
                    
                    <Form.Item
                        name="comment"
                        label="反馈意见"
                        rules={[{ required: true, message: '请填写反馈意见' }]}
                    >
                        <TextArea rows={4} placeholder="请对培训内容、讲师、环境等方面提出您的意见和建议" />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default MyTraining; 